/*
 * Copyright (c) 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.enterprise.gsa.util;

import com.google.enterprise.apis.client.GsaEntry;
import com.google.enterprise.apis.client.ImprovedGsaClient;
import com.google.enterprise.gsa.exception.ExportConfigFailedException;
import com.google.gdata.util.ServiceException;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;

/**
 * A utility class that can retrieve a Google Search Appliance's (GSA) configuration.
 *
 * @author todd.re...@gmail.com (Todd)
 */
public class GsaConfigExporter {

  /*
   * Utility class of which we don't want to create instances
   */
  private GsaConfigExporter() {}

  /**
   * Retrieves the "export" configuration file from the GSA.
   *
   * @param client the login information for a GSA
   * @param pw A password to apply to the configuration
   * @return The exported GSA configuration in one large {@code String}.
   *
   * @throws ExportConfigFailedException
   * @throws IOException
   * @throws ServiceException
   * @throws MalformedURLException
   */
  public static String getExportedConfig(ImprovedGsaClient client, String pw)
  throws ExportConfigFailedException, MalformedURLException, ServiceException, IOException {
    Map<String, String> queries = new HashMap<String, String>();
    queries.put("password", pw);

    GsaEntry entry = null;    

    entry = client.queryEntry("config", "importExport", queries);

    if (entry == null) {
      ExportConfigFailedException ecfe = new ExportConfigFailedException("entry was null");
      ecfe.fillInStackTrace();
      throw ecfe;
    }
    return entry.getGsaContent("xmlData");
  }
}
